package com.aigou.utils;

import java.sql.*;

/**
 * @Author Mr.LiFuXing
 * @Date 2024/12/2 18:46
 * @Title JDBCUtil
 * @Package com.aigou.utils
 */
public class JDBCUtil {


    // TODO 修改成自己的数据库配置信息
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/aigou";

    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    // 静态代码块，用于加载数据库驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to load JDBC driver.");
        }
    }

    // 获取数据库连接
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to get database connection.");
        }
    }
    public static int executeUpdate(String sql,Object... params){
        //创建连接，自动关闭
        try(Connection connection = DriverManager.getConnection(JDBC_URL,USERNAME,PASSWORD)){
            //创建命令对象
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //设置占位符参数
            for(int i = 0;i < params.length;i++){
                preparedStatement.setObject(i + 1,params[i]);
            }
            //执行命令
            int rows = preparedStatement.executeUpdate();
            return rows;
        }catch (SQLException ex){
            ex.printStackTrace();
            //向上抛出异常
            throw new RuntimeException(ex);
        }
    }

    // 关闭数据库连接、Statement和ResultSet
    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
